import React, { useState, useEffect } from 'react';
import { FileExcelOutlined, SearchOutlined } from '@ant-design/icons';
import { Input, Button, Spin, DatePicker, Checkbox,Modal } from 'antd';
import { useHistory } from 'react-router-dom';
import { openNotification_util, fetchsync_util, useexcelauto, dealnullorundenfined, convertISODateTimeToYYYYMMDDHHMMSS, use_olreport_bybbbm, convertISODateTimeToYYYYMMDD } from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'
var storage = window.localStorage;
import locale from 'antd/lib/date-picker/locale/zh_CN'
import logo from '../../../img/shipSRM/chlogo.png'
import Sortable_new from '../newmes/sortable_new.js';
import { useLatest } from 'ahooks';
import useStore from '../../useStore.js'
import { clearCache,useDidCache,useDidRecover ,dropByCacheKey } from 'react-router-cache-route';
import Qtrk_form from '../kcgl/qtrk_form.js';

const Crkmx = () => {
  const history = useHistory();
  const [crkmxlb, setCrkmxlb] = useState([])
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();
  //生产领料单
  const [ifshowmodal_scll, setifshowmodal_scll] = useState(false)
  const [ifshowmodal_cgrk, setifshowmodal_cgrk] = useState(false)
  const [ifshowmodal_xsck, setifshowmodal_xsck] = useState(false)
  const [ifshowmodal_qtrk, setifshowmodal_qtrk] = useState(false)


  const [isloading, setisloading] = useState(true)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [startDataStr, setStartDataStr] = useState()
  const [endDataStr, setEndtDataStr] = useState()
  const [ggxh, setGgxh] = useState('')
  const startDataStrref = useLatest(startDataStr)
  const endDataStrref = useLatest(endDataStr)
  const ggxhref = useLatest(ggxh)
  const [isHistory, setIsHistory] = useState(storage['Pc_crkmx_isHistory'] ? JSON.parse(storage['Pc_crkmx_isHistory']) : true)
  const [djlx, setDjlx] = useState(storage['Pc_crkmx_djlx'] ? JSON.parse(storage['Pc_crkmx_djlx']) : ['生产领料', '采购入库', '销售出库', '其他入库'])
  const [columnarr, setcolumnarr] = useState([
    { show: true, title: "序号", key: "xuhao", width: '60px', style: {} },
    { show: true, title: "源单类型", key: "ydlx", style: { fontWeight: "bold", }, searchtype: "select", },
    { show: true, title: "单据号", key: "djh", style: { fontSize: "12px", fontWeight: "bold"} },

    { show: true, title: "制单人", key: "create_by",width:'5vw', searchtype: "select", style: {} },
    { show: true, title: "仓库", key: "ck",width:'4vw', searchtype: "select", style: {} },
    { show: true, title: "日期", key: "create_time", style: {} },
    { show: true, title: "类别", key: "yjflmc",width:'4vw', searchtype: "select", style: {} },
    { show: true, title: "领料人", key: "llr",width:'5vw', searchtype: "select", style: {} },
    { show: true, title: "物料名称", key: "wlmc", style: { color: "#1d35e7" } },
    { show: true, title: "物料编码", key: "wlbm", style: { color: "#1d35e7" } },
    { show: true, title: "金蝶编码", key: "jdbm", style: { fontSize: "12px", } },
    { show: true, title: "规格", key: "ggxh", style: {} },
    { show: true, title: "类型", key: "lx",width:'4vw', style: {} },
    { show: true, title: "数量", key: "sl",width:'4vw', style: {} },
    { show: true, title: "单位", key: "dw",width:'4vw',style: {} },
    // { show: true, title: "批号", key: "ph", style: {} },
    { show: true, title: "版本号", key: "bbh",width:'5vw', style: {} },
  ])

  const djlxOptions = [
    {
      label: '生产领料',
      value: '生产领料',
    },
    {
      label: '采购入库',
      value: '采购入库',
    },
    {
      label: '销售出库',
      value: '销售出库',
    },
    {
      label: '其他入库',
      value: '其他入库',
    }
  ];


  const querylist = async () => {
    setisloading(true)
    let rtdata = await fetchsync_util("/admin/kcgl/queryCrkmxListAll", 'POST',
      { startDataStr: startDataStrref.current, endDataStr: endDataStrref.current, isHistory, djlx, ggxh: ggxhref.current }, "json")
    openNotification_util(rtdata.rtmessage)
    rtdata.resultdata.forEach(element => {
      element.czsj = element.czsj == null ? '' : convertISODateTimeToYYYYMMDD(element.czsj)
      element.create_time = element.create_time == null ? '' : convertISODateTimeToYYYYMMDD(element.create_time)

    });
    setCrkmxlb(dealnullorundenfined(rtdata.resultdata))
    setselectedRowKeys(dealnullorundenfined(rtdata.resultdata).map(item=>item.key))
    setselectedRows(dealnullorundenfined(rtdata.resultdata))
    setisloading(false)
  }

  const handleQuery = async (e, type) => {
    console.log(e);
    setisloading(true)
    let params 
    if (type == 'history') {
      params = { startDataStr: startDataStrref.current, endDataStr: endDataStrref.current, isHistory:e, djlx, ggxh: ggxhref.current }
    } else if (type == 'djlx') {
      params = { startDataStr: startDataStrref.current, endDataStr: endDataStrref.current, isHistory, djlx:e, ggxh: ggxhref.current }
    }
    let rtdata = await fetchsync_util("/admin/kcgl/queryCrkmxListAll", 'POST', params, "json")
    openNotification_util(rtdata.rtmessage)
    rtdata.resultdata.forEach(element => {
      element.czsj = element.czsj == null ? '' : convertISODateTimeToYYYYMMDD(element.czsj)
      element.create_time = element.create_time == null ? '' : convertISODateTimeToYYYYMMDD(element.create_time)

    });
    setCrkmxlb(dealnullorundenfined(rtdata.resultdata))
    setselectedRowKeys([])
    setselectedRows([])
    setisloading(false)
  }

  useEffect(() => {
    if (storage['Pc_crkmx']) {
      var result = JSON.parse(storage['Pc_crkmx'])
      setcolumnarr(result)
    }
    else {
      setcolumnarr(columnarr)
    }
    storage['Pc_crkmx_initsize'] ? setinitSize(storage['Pc_crkmx_initsize']) : setinitSize(1)


    querylist()

  }, [])



  const handleExprot = async () => {
    let filtercol = JSON.parse(JSON.stringify(columnarr)).filter(item => item.show == true)
    //console.crkmx("filtercol,", filtercol)
    useexcelauto(selectedRows, filtercol, '出入库明细列表')
  }

  //路由跳转
  const tonormal = (route) => {
    history.push({ pathname: route });
  }
  const handleselectfather = (selectedRows, selectedRowKeys) => {
    //console.crkmx(selectedRows)
    setselectedRows(selectedRows)
    setselectedRowKeys(selectedRowKeys)
  }

  const handleview=()=>{
if(selectedRows.length!=1){
  openNotification_util("只可选中一单查看")
  return
}

selectedRows[0].id=selectedRows[0].mainid

if(selectedRows[0].ydlx==="生产领料"){
  storage.pre_sclld_item = JSON.stringify({ data: selectedRows[0], type: "view" })
  dropByCacheKey("sclld_form")
  setifshowmodal_scll(true)
}else if(selectedRows[0].ydlx==="采购入库"){
  storage.pre_cgrkd_item = JSON.stringify({ data: selectedRows[0], type: "view" })
  dropByCacheKey("cgrkd_form")
  setifshowmodal_cgrk(true)
}else if(selectedRows[0].ydlx==="销售出库"){
  storage.pre_xsckd_item = JSON.stringify({ data: selectedRows[0], type: "view" })
  dropByCacheKey("xsckd_form")
  setifshowmodal_xsck(true)
}else if(selectedRows[0].ydlx==="其他入库"){
  storage.pre_qtrk_item = JSON.stringify({ data: selectedRows[0], type: "view" })
  dropByCacheKey("qtrk_form")
  setifshowmodal_qtrk(true)
}



  }


  return (
    <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}>

      <Modal open={ifshowmodal_scll} style={{ top: "5vh", backgroundColor: "rgba(0,0,0,0.8)" }} width="96%" onCancel={() => { setifshowmodal_scll(false) }}
      title="穿透查看"
        bodyStyle={{ width: "96vw", position: "relative", height: "80vh", borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}
        okButtonProps={{ style: { display: "none" } }} cancelButtonProps={{ style: { display: "none" } }}
        destroyOnClose={true}
      ><Sclld_form hiddenbutton={true} transfer={true} transferdata={[]}/></Modal>
      <Modal open={ifshowmodal_cgrk} style={{ top: "5vh", backgroundColor: "rgba(0,0,0,0.8)" }} width="96%" onCancel={() => { setifshowmodal_cgrk(false) }}
      title="穿透查看"
        bodyStyle={{ width: "96vw", position: "relative", height: "80vh", borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}
        okButtonProps={{ style: { display: "none" } }} cancelButtonProps={{ style: { display: "none" } }}
        destroyOnClose={true}
      ><Cgrkd_form hiddenbutton={true} transfer={true} transferdata={[]}/></Modal>
      <Modal open={ifshowmodal_xsck} style={{ top: "5vh", backgroundColor: "rgba(0,0,0,0.8)" }} width="96%" onCancel={() => { setifshowmodal_xsck(false) }}
      title="穿透查看"
        bodyStyle={{ width: "96vw", position: "relative", height: "80vh", borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}
        okButtonProps={{ style: { display: "none" } }} cancelButtonProps={{ style: { display: "none" } }}
        destroyOnClose={true}
      ><Xsckd_form hiddenbutton={true} transfer={true} transferdata={[]}/></Modal>
      <Modal open={ifshowmodal_qtrk} style={{ top: "5vh", backgroundColor: "rgba(0,0,0,0.8)" }} width="96%" onCancel={() => { setifshowmodal_qtrk(false) }}
      title="穿透查看"
        bodyStyle={{ width: "96vw", position: "relative", height: "80vh", borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}
        okButtonProps={{ style: { display: "none" } }} cancelButtonProps={{ style: { display: "none" } }}
        destroyOnClose={true}
      ><Qtrk_form hiddenbutton={true} transfer={true} transferdata={[]}/></Modal>


      <div style={styles.kshcontainer}>
        <div style={{
            width: "99%", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw"
        }}>
          <div style={styleobj.linestyleflex}>
            &nbsp;&nbsp;&nbsp;<span style={{ fontSize: "0.7rem", fontWeight: "800" }}>开始日期：</span><DatePicker locale={locale}
              style={{ width: "200px" }} onChange={(e, dateString) => setStartDataStr(dateString)} /> &nbsp; &nbsp;

            <span style={{ fontSize: "0.7rem", fontWeight: "800" }}>结束日期：</span> <DatePicker locale={locale}
              style={{ width: "200px" }} onChange={(e, datestring) => setEndtDataStr(datestring)} />  &nbsp; &nbsp;
            <span style={{ fontSize: "0.7rem", fontWeight: "800" }}>规格型号：</span>
            <Input style={{ width: "200px" }} onChange={(e) => setGgxh(e.target.value)} />  &nbsp; &nbsp;

            &nbsp;&nbsp;&nbsp;  <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : querylist() }}><ReloadOutlined />刷新</Button>

                  &nbsp;&nbsp;&nbsp;  <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleview() }}><SearchOutlined />查看源单</Button>
            
            
            &nbsp;&nbsp;&nbsp;  <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleExprot}><FileExcelOutlined />导 出</Button>
                  <Sortable_new tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
              storageName="Pc_crkmx" style={{ position: 'absolute', right: '2vw', top: '0.5rem', fontSize: "1.5rem" }}
              initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage['Pc_crkmx_initsize'] = data; }}
            />
          </div>
          <div style={styleobj.linestyleflex}>
          &nbsp;&nbsp;&nbsp; <Checkbox checked={isHistory} onChange={(e) => { setIsHistory(e.target.checked);  storage['Pc_crkmx_isHistory'] = JSON.stringify(e.target.checked); handleQuery(e.target.checked, 'history') }}>历史单据</Checkbox>
            &nbsp;&nbsp;&nbsp; <Checkbox.Group value={djlx} options={djlxOptions} onChange={(e) => { setDjlx(e); storage['Pc_crkmx_djlx'] = JSON.stringify(e); handleQuery(e, 'djlx') }} />
    
             &nbsp;&nbsp;&nbsp;<span style={{ fontSize: "0.7rem", fontWeight: "800" }}>数量合计：{selectedRows.reduce((a,b)=>a+b.sl,0).toFixed(2)}</span>
          </div>


          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}><Spin /></div>)
            :
            <div style={{ width: "100%", left: "0", margin: "auto" }}>
              <Custom_table_hooks_config tabledata={crkmxlb} tablecolnum={columnarr}
                sfdoubleclick="false" ifhiddencchangeselecttype="true"
                width={`${100*initSize}%`}
                scroll={{ y: 'calc(100vh - 280px)'}}

                selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
                calcolor={(text) => {
                  return text == "入库" ? '#13d601' :
                    text == "出库" ? '#a91f24' : 'black'
                }}
                handleselectson={(selectedRows, selectedRowKeys) => { handleselectfather(selectedRows, selectedRowKeys) }}
              />
            </div>
          }
        </div>

      </div>
    </div>
  )
}


export default Crkmx

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
butdcstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
butmainstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


kshcontainer: {
  width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
  color: "black"
},
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96%", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}